import { Injectable, Inject } from '@nestjs/common';
import { InjectEntityManager, InjectRepository } from '@nestjs/typeorm';
import { EntityManager, In, Like, Repository } from 'typeorm';
import SysTag from '@/entities/admin/sys-tags.entity';
import { ApiException } from 'src/common/exceptions/api.exception';
import { CreateTagDto, UpdateArticleTagDto, DeleteTagDto, ListTagDto } from './tag.dto';
@Injectable()
export class SysTagService {
  constructor(@InjectRepository(SysTag) private readonly tagRepository: Repository<SysTag>) {}

  /**
   * 添加标签
   */
  async create(tag: CreateTagDto) {
    const { name, categoryId, status } = tag;
    const existTag = await this.tagRepository.findOne({ where: { name } });
    if (existTag) {
      throw new ApiException(10000);
    }
    const tagObj = new SysTag();
    tagObj.name = name;
    tagObj.categoryId = categoryId;
    tagObj.status = status;
    const newTag = await this.tagRepository.save(tagObj);
    return newTag;
  }

  /**
   * 获取所有标签
   */
  async findAll(queryParams) {
    const { limit, page } = queryParams;
    const qb = this.tagRepository
      .createQueryBuilder('tag')
      .orderBy('tag.created_at', 'ASC')
      .limit(limit)
      .offset((page - 1) * limit);
    const data = await qb.getMany();
    // data.forEach((d) => {
    //   Object.assign(d, { articleCount: d.articles?.length });
    //   delete d.articles;
    // });

    return data;
  }

  /**
   * 获取指定标签
   * @param id
   */
  async findById(id): Promise<SysTag> {
    const data = await this.tagRepository
      .createQueryBuilder('tag')
      .where('tag.id=:id')
      .orWhere('tag.name=:id')
      .orWhere('tag.categoryId=:id')
      .setParameter('id', id)
      .getOne();

    return data;
  }

  /**
   * 获取指定标签信息，包含相关文章
   * @param id
   */
  async getArticleById(id): Promise<SysTag> {
    const data = await this.tagRepository
      .createQueryBuilder('tag')
      .leftJoinAndSelect('tag.articles', 'articles')
      .orderBy('articles.updateAt', 'DESC')
      .where('tag.id=:id')
      .orWhere('tag.name=:id')
      .orWhere('tag.categoryId=:id')
      .setParameter('id', id)
      .getOne();

    // if (status) {
    //   data.articles = data.articles.filter((a) => a.status === status);
    //   return data;
    // }
    return data;
  }

  async findByIds(ids): Promise<Array<SysTag>> {
    return this.tagRepository.findBy({ id: ids });
  }

  /**
   * 更新标签
   * @param id
   * @param tag
   */
  async updateById(dto): Promise<SysTag> {
    const oldTag = await this.tagRepository.findOne({ where: { id: dto.id } });
    const updatedTag = await this.tagRepository.merge(oldTag, dto);
    return this.tagRepository.save(updatedTag);
  }

  /**
   * 删除标签
   * @param id
   */
  async deleteById(id) {
    try {
      const tag = await this.tagRepository.findOne({ where: { id } });
      await this.tagRepository.remove(tag);
      return true;
    } catch (e) {
      throw new ApiException(12000);
    }
  }
}
